package cn.psvmc.cxzapi.controller.order;

import cn.psvmc.cxzapi.model.common.OrderEntity;
import cn.psvmc.cxzapi.model.order.TOrderDelivery;
import cn.psvmc.cxzapi.response.PageResult2;
import cn.psvmc.cxzapi.response.Result;
import cn.psvmc.cxzapi.response.ResultGenerator;
import cn.psvmc.cxzapi.service.order.TOrderDeliveryService;
import cn.psvmc.cxzapi.util.PageUtil;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 订单快递
 * @Author auto
 * @Date 2024-08-12
 */
@RestController
@RequestMapping("/delivery")
@Slf4j
public class TOrderDeliveryController {

    @Resource
    private TOrderDeliveryService tOrderDeliveryService;

    /**
     * @Description 发货
     * @Date 2024/8/23 12:23
     * @Author YWX
     * @Param [tOrderDelivery]
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    @PostMapping("/add")
    public Result add(@RequestBody TOrderDelivery tOrderDelivery) {
        Integer deliveryType = tOrderDelivery.getDeliveryType();
        ToolUtils.validation(new Object[]{
                deliveryType, "快递类型", 1
                , tOrderDelivery.getOrderCode(), "订单号", 2
                , tOrderDelivery.getType(), "发货类型", 1
        });
        if (!deliveryType.equals(99) && ToolUtils.isEmpty(tOrderDelivery.getTrackingCode())) {
            throw new IllegalArgumentException("快递单号不能为空！");
        }
        tOrderDeliveryService.add(tOrderDelivery);
        return ResultGenerator.genSuccessResult("保存成功！");
    }

    /**
     * @Description 批量发货
     * @Date 2024/8/23 11:05
     * @Author YWX
     * @Param [tOrderDelivery]
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    @PostMapping("/batch_add")
    public Result batchAdd(@RequestBody TOrderDelivery tOrderDelivery) {
        ToolUtils.validation(new Object[]{
                tOrderDelivery.getDeliveryType(), "快递类型", 1
        });
        tOrderDeliveryService.batchAdd(tOrderDelivery);
        return ResultGenerator.genSuccessResult("发货成功！");
    }

    /**
     * @Description 物流信息
     * @Date 2024/8/23 12:23
     * @Author YWX
     * @Param [tOrderDelivery]
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    @PostMapping("/detail")
    public Result detail(@RequestBody TOrderDelivery tOrderDelivery) {
        String orderCode = tOrderDelivery.getOrderCode();
        Integer type = tOrderDelivery.getType();
        ToolUtils.validation(new Object[]{
                orderCode, "订单号", 2
                , type, "快递类型", 1
        });
        return ResultGenerator.genSuccessResult("查询成功", tOrderDeliveryService.detail(orderCode, type));
    }

    /**
     * @Description 发货工作台
     * @Date 2024/8/23 12:28
     * @Author YWX
     * @Param [entity]
     * @Return cn.psvmc.cxzapi.response.PageResult2
     **/
    @PostMapping("/list")
    public PageResult2 list(@RequestBody OrderEntity entity) {
        Page<TOrderDelivery> queryPage = new Page<>(entity.getPage(), entity.getSize());
        return PageUtil.getPageResult2(tOrderDeliveryService.list(queryPage, entity));
    }

    /**
     * @Description 德邦标准轨迹订阅
     * @Date 2024/9/30 11:10
     * @Author YWX
     * @Param [req, resp]
     * @Return void
     **/
//    @PostMapping("/db_trace")
//    protected void dbPost(HttpServletRequest req, HttpServletResponse resp)
//            throws IOException {
//        //时间戳
//        String timestamp = req.getParameter("timestamp");
//        //摘要
//        String digest = req.getParameter("digest");
//        //参数
//        String params = req.getParameter("params");
//        //TOrderDeliveryController.log.info("德邦标准轨迹订阅: {}", params);
//        //时间戳验证使用，判断请求是否在有效的时间戳范围内，时间戳范围根据情况自行定义
//        long sendTime = Long.parseLong(timestamp);
//        long now = System.currentTimeMillis();
//        long effectiveTimestamp = 1800000;
//        //摘要验证使用 appkey为双方约定
//        String appkey = ConfigKey.appkey;
//        String expectDigest = SecurityUtil.getDigest(params + appkey + timestamp);
//        SimpleResultInfo resultInfo = new SimpleResultInfo();
//        resultInfo.setResultCode("true");
//        resultInfo.setResult(ResultCode.SUCCESS.getNumber());
//        resultInfo.setReason("成功");
//        if (Math.abs(now - sendTime) > effectiveTimestamp) {//时间戳验证
//            resultInfo.setResultCode("false");
//            resultInfo.setResult(ResultCode.TIMESTAMP_ERROR.getNumber());
//            resultInfo.setReason("时间戳失败");
//        } else if (!expectDigest.equals(digest.trim())) {//摘要验证
//            resultInfo.setResultCode("false");
//            resultInfo.setResult(ResultCode.DIGEST_ERROR.getNumber());
//            resultInfo.setReason("摘要验证失败");
//        }
//        //业务处理
//        tOrderDeliveryService.saveDbTrace(params);
//
//        String response = FastJsonUtil.toJSONString(resultInfo);
//        resp.setCharacterEncoding("UTF-8");
//        PrintWriter pw = null;
//        try {
//            pw = resp.getWriter();
//            pw.println(response);
//            pw.flush();
//        } finally {
//            pw.close();
//        }
//    }

    @PostMapping("/sf_trace")
    public String sfTrace(@RequestBody String notificationBody) {
        try {
            //解析并验证通知内容
            //TOrderDeliveryController.log.info("顺丰标准轨迹订阅: {}", notificationBody);

            // 根据实际情况进行处理，例如更新订单状态
            return "success";
        } catch (Exception e) {
            TOrderDeliveryController.log.error("顺丰标准轨迹订阅失败: {}", e.getMessage());
            return "failure";
        }
    }

    /**
     * @Description 获取发货工作台状态数量
     * @Date 2024/11/16 23:03
     * @Author YWX
     * @Param [entity]
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    @PostMapping("/get_status_num")
    public Result getStatusNum(@RequestBody OrderEntity entity) {
        return ResultGenerator.genSuccessResult(tOrderDeliveryService.getStatusNum(entity));
    }
}
